package com.oauth.components.client.rpc;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.oauth.components.client.rpc.exception.SessionExpiredException;

public abstract class OAuthAsnyCallBack<T> implements AsyncCallback<T> {

	public final static DialogBox dialogBox = new DialogBox();
	public final static Button closeButton = new Button("Close");
	public final static HTML serverResponseLabel = new HTML();
	public final static VerticalPanel dialogVPanel = new VerticalPanel();

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server.<br/> Your might be signed out or check your network "
			+ "connection";
	private static final String SESSION_EXPIRED_MESSAGE = "Your session is expired. <br/> Redirecting to login page....";
	private static final String SITE_BASE_URL = GWT.getHostPageBaseURL();

	public OAuthAsnyCallBack() {
		// Create the popup dialog box
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");

		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);
		dialogBox.setGlassEnabled(true);
		serverResponseLabel.addStyleName("serverResponseLabelError");

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
	}

	public void onFailure(Throwable pCaught) {
		try {
			throw pCaught;
		} catch (SessionExpiredException e) {
			Window.Location.assign(SITE_BASE_URL);
		} catch (IncompatibleRemoteServiceException e) {
			dialogBox.setText("Incompatible service error");
			serverResponseLabel.setHTML(SESSION_EXPIRED_MESSAGE);
			Window.Location.assign(SITE_BASE_URL);
		} catch (Throwable e) {
			dialogBox.setText("Remote Procedure Call - Failure");
			serverResponseLabel.setHTML(SERVER_ERROR);
			closeButton.setFocus(true);
			dialogBox.center();
		}
	}
}
